﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using WebChatServer.Models;

namespace WebChatServer.Controllers
{
    [HttpHeader("Access-Control-Allow-Origin", "*")]
    [HttpHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")]

    public class ChatController : ApiController
    {
        ChatRepository repository = new ChatRepository();
        ChatOnlineEntities entities = new ChatOnlineEntities();
        //
        // GET: /Chat/
        public void Options()
        {

        }

        public GroupMsgChat Get(string id)
        {
            Message[] msg = repository.Check(id);
            if (msg != null)
            {
                ChatMsg[] chatMsg = new ChatMsg[msg.Length];
                for (int i = 0; i < msg.Length; i++)
                {
                    //repository.Delete(msg[i]);
                    chatMsg[i] = new ChatMsg(){UserId = id, Message = msg[i].Message1, FriendId = msg[i].UserId};
                    repository.Delete(msg[i]);
                }
                //entities.SaveChanges();

                GroupMsgChat groupMsg = new GroupMsgChat(){Chat = chatMsg};                
                return groupMsg;
            }
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NoContent);
            //throw new HttpResponseException(response);
            return null;
        }

        public string Post(ChatMsg msg)
        {
            repository.Chat(msg.UserId, msg.FriendId, msg.Message);
            return "post";
        }
        
    }
}
